<template>
  <div>
    <DynamicTable
      row-key="id"
      header-title="文件管理"
      :data-request="loadKnowledgeFileList"
      :columns="columns"
      bordered
      :immediate="false"
      size="small"
      :search-params="{ knowledgeBaseId }"
    >
      <template #toolbar>
        <a-button
          type="primary"
          @click="openMenuModal({})"
        >
          上传文件
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onBeforeMount } from 'vue';
  import { useRoute } from 'vue-router';
  import {
    baseColumns,
    searchFormSchema,
    type TableListItem,
    type TableColumnItem,
  } from './columns';
  import { baseSchemas } from './formSchemas';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/';
  import Api from '@/api/';
  import { useTabsViewStore } from '@/store/modules/tabsView';
  import helper from '@/utils/helper';

  defineOptions({
    name: 'KnowledgeFile',
  });

  const tabsViewStore = useTabsViewStore();
  const route = useRoute();
  const knowledgeBaseId = ref(String(route.params.id));
  let knowledgeBaseList: LabelValueOptions = [];

  const [DynamicTable, dynamicTableInstance] = useTable({
    formProps: {
      schemas: searchFormSchema,
      initialValues: { knowledgeBaseId: knowledgeBaseId.value },
      onReset(model) {
        if (model?.knowledgeBaseId) {
          knowledgeBaseId.value = model.knowledgeBaseId;
        }
      },
    },
  });

  const [showModal] = useFormModal();

  onBeforeMount(async () => {
    const data = await Api.knowledgeBase.knowledgeBaseGetAll();
    if (data) {
      knowledgeBaseList = data.map((n) => ({ label: n.name, value: n.id }));

      const targetBase = data.find((n) => n.id === knowledgeBaseId.value);
      tabsViewStore.updateTabTitle(`${route.meta.title}(${targetBase?.name})`);
      // 动态更新搜索表单项
      dynamicTableInstance?.getSearchFormRef()?.updateSchema?.([
        {
          field: 'knowledgeBaseId',
          componentProps: {
            options: knowledgeBaseList,
            onChange(value) {
              knowledgeBaseId.value = value;
            },
          },
        },
      ]);
    }
    dynamicTableInstance?.reload();
  });

  /**
   * @description 加载知识库文件列表（处理返回值可能为null的情况）
   */
  const loadKnowledgeFileList = async (params: Recordable<any>) => {
    const result = await Api.knowledgeFile.knowledgeFileList(params);
    return result || [];
  };

  /**
   * @description 打开上传文件弹窗
   */
  const openMenuModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: '上传文件',
        width: '50%',
        onFinish: async (values) => {
          if (record.id) {
            await Api.knowledgeFile.knowledgeFileUpdate({ id: record.id }, values);
          } else {
            await Api.knowledgeFile.knowledgeFileCreate(values);
          }

          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 120,
        schemas: baseSchemas,
      },
    });

    formRef?.updateSchema({
      field: 'knowledgeBaseId',
      componentProps: {
        options: knowledgeBaseList,
        disabled: !!knowledgeBaseId.value,
      },
    });

    formRef?.setFieldsValue({
      knowledgeBaseId: knowledgeBaseId.value,
      ...record,
    });
  };

  /**
   * @description 下载文件
   */
  const downloadFile = async (record: TableListItem) => {
    
    await Api.file.directdownload(record.fileMD5);
  };

  /**
   * @description 删除文件
   */
  const delRowConfirm = async (record: TableListItem) => {
    await Api.knowledgeFile.knowledgeFileDelete({ id: record.id });
    dynamicTableInstance?.reload();
  };

  /**
   * @description 向量化文件
   */
  const embedFile = async (record: TableListItem) => {
    try {
      await Api.knowledgeFile.knowledgeFileEmbedding(record.knowledgeBaseId, record.id);
      // 向量化成功后刷新列表
      dynamicTableInstance?.reload();
    } catch (error) {
      console.error('向量化文件失败:', error);
    }
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      hideInSearch: true,
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openMenuModal(record),
        },
        {
          label: '向量化',
          
          tooltip: record.isEmbedding ? '文件已向量化' : '',
          onClick: () => embedFile(record),
        },
        {
          label: '下载',
          onClick: () => downloadFile(record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '你确定要删除吗？',
            placement: 'left',
            onConfirm: () => delRowConfirm(record),
          },
        },
      ],
    },
  ];
</script> 